package com.swak.consistency.core.aspect;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.Ordered;

import com.swak.annotation.Consistency;

/**
 * 定义： 切面
 * 
 * @author DELL
 */
@Aspect
public class ConsistencyAspect implements Ordered {

	/**
	 * 拦截Tcc等注解 {@linkplain Consistency}
	 */
	@Pointcut("@annotation(com.swak.annotation.Tcc) || @annotation(com.swak.annotation.ReliableMsg)")
	public void Consistency_Pointcut_Interceptor() {
	}

	/**
	 * 拦截器处理方法： 只要执行 confirm 和 cancel
	 * 
	 * @param point
	 * @return
	 * @throws Throwable
	 */
	@Around("Consistency_Pointcut_Interceptor()")
	public Object around(ProceedingJoinPoint point) throws Throwable {
		return ConsistencyProceeding.of().setTarget(point.getTarget().getClass()).setArgs(point.getArgs())
				.setMethod(((MethodSignature) point.getSignature()).getMethod()).setProceeding(() -> {
					return point.proceed();
				}).complete();

	}

	/**
	 * Aop的顺序要早于spring的事务
	 * 注意Order序号要小于{@link org.springframework.aop.interceptor.ExposeInvocationInterceptor},
	 * PriorityOrdered.HIGHEST_PRECEDENCE + 1
	 */
	@Override
	public int getOrder() {
		return Ordered.HIGHEST_PRECEDENCE;
	}

}
